package com.sporadic.wx.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sporadic.wx.pojo.WxEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

@Service
@Slf4j
public class WxAuthentication {
    @Autowired
    private WxEntity wxEntity;
    @Autowired
    private RestTemplate restTemplate;

    public JSONObject getSessionKeyOrOpenId(String code) {
        //微信端登录code
        String wxCode = code;
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        //封账请求参数
        MultiValueMap<String, String> requestUrlParam = new LinkedMultiValueMap<String, String>();
        //小程序appId
        requestUrlParam.add("appid", wxEntity.getAppid());
        requestUrlParam.add("secret", wxEntity.getAppsecret());
        //小程序端返回的code
        requestUrlParam.add("js_code", wxCode);
        //默认参数
        requestUrlParam.add("grant_type", "authorization_code");
        HttpEntity requestEntity = new HttpEntity(requestUrlParam,null);
        //发送post请求读取调用微信接口获取openid用户唯一标识
        String result = restTemplate.postForObject(requestUrl, requestEntity, String.class);
        log.info("微信响应:" +result);
        return JSON.parseObject(result);
    }

    /**
     * 解密用户电话
     * @param keyStr sessionkey
     * @param ivStr  ivData
     * @param encDataStr 带解密数据
     * @return
     * @throws Exception
     * @author pangxianhe
     * @date 2018年10月22日
     */
    public String decrypt(String keyStr, String ivStr, String encDataStr)throws Exception {
        byte[] encData = Base64Utils.decode(encDataStr.getBytes());
        byte[] iv = Base64Utils.decode(ivStr.getBytes());
        byte[] key = Base64Utils.decode(keyStr.getBytes());
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return new String(cipher.doFinal(encData),"UTF-8");
    }
}
